package com.dev.weixin.tools.utils.policy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import com.dev.weixin.tools.models.exceptions.ErrorMsgException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 下载策略强制下载（无法判定下载文件类型）
 * @author 飘渺青衣
 * @see
 */
public class ForceDownloadRequestPolicy extends JsonRequestPolicy<File> {

	private String filepath;

	/**
	 * @param url
	 * @param encoding
	 * @param getParameters
	 * @param jsonObject
	 * @param filepath 下载路径（包括文件名）
	 */
	public ForceDownloadRequestPolicy(String url, String encoding,
			Map<String, String> getParameters, Object jsonObject, String filepath) {
		super(url, encoding, getParameters, jsonObject, File.class);
		this.filepath = filepath;
	}

	@Override
	public File response(HttpResponse response, HttpEntity entity,
			ObjectMapper mapper) throws ErrorMsgException {
		FileOutputStream fos = null;
		InputStream is = null;
		try {
			 LOG.info(filepath);
         	byte[] buff = new byte[8192];
         	int len = 0;
         	fos = new FileOutputStream(filepath);
         	is = entity.getContent();
         	while((len = is.read(buff)) > 0) {
         		fos.write(buff, 0, len);
         		try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
					}
         	}
         	return new File(filepath);
		} catch (FileNotFoundException e) {
			LOG.error(e);
		} catch (IllegalStateException e) {
			LOG.error(e);
		} catch (IOException e) {
			LOG.error(e);
		} finally {
        	if(is != null) {
        		try {
					is.close();
				} catch (IOException e) {}
        	}
        	if(fos != null) {
        		try {
					fos.close();
				} catch (IOException e) {}
        	}
        }
		return null;
	}

	public String getFilepath() {
		return filepath;
	}

}
